/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddCenter_Panel.java
 *
 * Created on 29-10-2014, 16:05:27
 */
package frame;

import Manager.HibernateUtil;
import entities.Center;
import entities.District;
import entities.Province;
import entities.Ward;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author aptech
 */
public class AddCenter_Panel extends javax.swing.JPanel {

    Ward w = null;
    final String name = "ServerAdmin";
    Ward wc = null;
    Center c = null;
    List<Province> lct;
    List<District> ldt;
    List<Ward> lwd;
    /**
     * Creates new form AddCenter_Panel
     */
    public AddCenter_Panel() {
        initComponents();
        getCity();
        getDistrict();
        getWard();
    }
    private final SessionFactory sf = HibernateUtil.getSessionFactory();

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        tfnumber = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        tfstreet = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cbbdistrict = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        cbbward = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        tfname = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        cbbcity = new javax.swing.JComboBox();
        jSeparator1 = new javax.swing.JSeparator();
        btnAdd = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "ADD CENTER INFORMATION", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BELOW_TOP, new java.awt.Font("Arial", 0, 20), new java.awt.Color(0, 164, 250))); // NOI18N
        jPanel2.setPreferredSize(new java.awt.Dimension(400, 457));

        jLabel1.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 164, 250));
        jLabel1.setText("Number:");

        tfnumber.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(0, 164, 250));
        jLabel2.setText("Street:");

        tfstreet.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel3.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(0, 164, 250));
        jLabel3.setText("District:");

        cbbdistrict.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cbbdistrict.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Binh Thanh", "Thu Duc", "Tan Binh" }));
        cbbdistrict.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbbdistrictItemStateChanged(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(0, 164, 250));
        jLabel4.setText("Ward:");

        cbbward.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cbbward.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "25", "24", "1", "2", "3" }));

        jLabel5.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(0, 164, 250));
        jLabel5.setText("Name:");

        tfname.setEditable(false);
        tfname.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel7.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(0, 164, 250));
        jLabel7.setText("City:");

        cbbcity.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cbbcity.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ho Chi Minh", "Ha Noi", "Vung Tau" }));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(tfname, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbbcity, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tfstreet, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
                            .addComponent(tfnumber, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cbbward, javax.swing.GroupLayout.Alignment.TRAILING, 0, 208, Short.MAX_VALUE)
                            .addComponent(cbbdistrict, javax.swing.GroupLayout.Alignment.TRAILING, 0, 208, Short.MAX_VALUE))))
                .addGap(0, 0, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cbbcity, cbbdistrict, cbbward, tfname, tfnumber, tfstreet});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel2, jLabel3, jLabel4, jLabel5, jLabel7});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfnumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfstreet, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbbcity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(cbbdistrict, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbbward, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(24, 24, 24))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {cbbcity, cbbdistrict, cbbward, jLabel1, jLabel2, jLabel3, jLabel4, jLabel7, tfnumber, tfstreet});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel5, tfname});

        btnAdd.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
        btnAdd.setForeground(new java.awt.Color(0, 164, 250));
        btnAdd.setText("ADD");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnReset.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
        btnReset.setForeground(new java.awt.Color(0, 164, 250));
        btnReset.setText("RESET");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(29, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(btnReset)
                        .addGap(82, 82, 82))))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdd, btnReset});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(23, 23, 23))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 457, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        tfname.setText("");
        tfnumber.setText("");
        tfstreet.setText("");
    }//GEN-LAST:event_btnResetActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        String wa = cbbward.getItemAt(cbbward.getSelectedIndex()).toString();
        String dis = cbbdistrict.getItemAt(cbbdistrict.getSelectedIndex()).toString();
        tfname.setText(wa + " - " + dis);
        if (!validate_null()) {
            JOptionPane.showMessageDialog(this, "Please complete the information", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            addCenter();
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void cbbdistrictItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbbdistrictItemStateChanged
        // TODO add your handling code here:
        getWard();
    }//GEN-LAST:event_cbbdistrictItemStateChanged

    private boolean validate_null() {

        if (tfnumber.getText().equals("")) {
            tfnumber.requestFocus();
            tfnumber.setBackground(Color.pink);
            return false;
        } else {
            tfnumber.setBackground(Color.white);
            if (tfstreet.getText().equals("")) {
                tfstreet.requestFocus();
                tfstreet.setBackground(Color.pink);
                return false;
            } else {
                tfstreet.setBackground(Color.white);
                return true;
            }
        }

    }

    private Center validate_name(String name) {
        Center ct = null;
        try {
            ct = (Center) sf.getCurrentSession().get(Center.class, name);
//            String sql="from Center C where C.name = :name";
//            Query query = ss.createQuery(sql);
//            query.setParameter("name", name);
//            list = query.list();
        } catch (Exception e) {
            return null;
        } finally {
            sf.getCurrentSession().close();
        }
//        return list;
        return ct;
    }

    private void addCenter() {
        String s = cbbward.getItemAt(cbbward.getSelectedIndex()).toString();
        c = new Center();
        c.setAddress(tfnumber.getText() + " " + tfstreet.getText());
        c.setWard(w);
        c.setName(tfname.getText());
        Session ss = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = ss.beginTransaction();
            ss.save(c);
            transaction.commit();
            JOptionPane.showMessageDialog(null, "Add center successful");
        } catch (Exception e) {
            transaction.rollback();
            JOptionPane.showMessageDialog(null, "Can't add.");
        } finally {
            ss.close();
        }
    }

    private Ward findWard(String ward) {
        try {
            w = (Ward) sf.getCurrentSession().get(Ward.class, ward);
        } catch (HibernateException ex) {
            System.err.println(ex);
        } finally {
            sf.getCurrentSession().close();
        }
        return w;
    }

    private void getCity() {
        cbbcity.removeAllItems();
        lct = null;
        try {
            sf.getCurrentSession().beginTransaction();
            lct=sf.getCurrentSession().createCriteria(Province.class).list();

        } catch (HibernateException ex) {
            System.err.println(ex);

        } finally {
            sf.getCurrentSession().close();
        }
        for (Province p : lct) {
            cbbcity.addItem(p.getName());
        }
    }

    private void getDistrict() {
        ldt = null;
//        ldt = 
        cbbdistrict.removeAllItems();
        int city = cbbcity.getSelectedIndex();
        String city_id = lct.get(city).getIdProvince();
        Province pro = lct.get(city);
        
        try {
            //List<District> llll = new ArrayList<District>();
            Iterator<District> ds = pro.getDistricts().iterator();
            while (ds.hasNext()) {
                District district = ds.next();
                //System.out.println("ajdkjask k jf"+district.getName());
                //District dt = new District(district.getIdDistrict(), pro, district.getName());
                //ldt.add(district);
                System.out.println(district.getName());
                Iterator<Ward> wd = district.getWards().iterator();
                while (wd.hasNext()) {
                    Ward ward = wd.next();
                    System.out.println(ward.getName());
                    
                }
                
                cbbdistrict.addItem(district.getName());
            }
                    
//        for (District d : ldt) {
//            cbbdistrict.addItem(d.getName());
//        }
        //adminserver
//            String sql="from District D where D.province = :province";
//            Query query = sf.getCurrentSession().createQuery(sql);
//            query.setParameter("province", sf.getCurrentSession().get(Province.class, city_id));
//            ldt = query.list();
            //ldt = sf.getCurrentSession().createCriteria(District.class).list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sf.getCurrentSession().close();
        }
    }
    
    
    private void getWard() {
        cbbward.removeAllItems();
        try {
        int iddistrict = cbbdistrict.getSelectedIndex();
        sf.getCurrentSession().beginTransaction();
        District ds = ldt.get(iddistrict);
//                (District) sf.getCurrentSession().get(District.class, iddistrict);
            Iterator<Ward> wd = ds.getWards().iterator();
            while (wd.hasNext()) {
                Ward ward = wd.next();
                cbbward.addItem(ward.getName());
                //lwd.add(ward);
            }
        } catch (Exception e) {
        }finally{
            sf.getCurrentSession().close();
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnReset;
    private javax.swing.JComboBox cbbcity;
    private javax.swing.JComboBox cbbdistrict;
    private javax.swing.JComboBox cbbward;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField tfname;
    private javax.swing.JTextField tfnumber;
    private javax.swing.JTextField tfstreet;
    // End of variables declaration//GEN-END:variables

}
